<?php

namespace App\Admin\Controllers\Statistics;

use App\Models\Community;
use App\Models\Gift\Tag;
use App\Models\Member\Price;

use App\Models\Sys\Gift;
use App\Models\User\User;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Show;
use Illuminate\Http\Request;
use Validator;

class NearbyController extends Controller
{
    use ModelForm;
    public $header = '附近列表';

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header($this->header);
            $content->description('description');

            $content->body($this->grid());
        });
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     * @return Content
     */
    public function show($id, Content $content)
    {
        return $content
            ->header($this->header)
            ->description('Detail')
            ->body($this->detail($id));
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header($this->header);
            $content->description('description');

            $content->body($this->form()->edit($id));
        });
    }


    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header($this->header);
            $content->description('description');

            $content->body($this->form());
        });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Admin::grid(Community::class, function (Grid $grid) {

            $grid->model()->where('show', 1)->orderBy('community_id', 'desc');
            $grid->community_id('编号');
            $grid->images('图片')->display(function ($v) {
                $v = explode(',', $v);
                if ($v) {
                    return $v[0];
                }
            })->image('', 50);
            $grid->content('内容')->style('max-width:400px');
            $grid->user()->username('发布用户');
            $grid->create_at('发布时间');
            $grid->column('相关')->display(function () {
                return '礼物：' . $this->gift_num . '<br>' . '阅读：' . $this->page_view . '<br>' . '评论：' . $this->comment_num;
            });

            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->disableEdit();
            });

            $grid->filter(function (Grid\Filter $filter) {
                $filter->disableIdFilter();
                $filter->where(function ($query) {
                    $input = $this->input;
                    $query->whereHas('user', function ($query) use ($input) {
                        $query->where('username', 'like', "%$input%");
                    });

                }, '发布用户', 'username');

                $filter->between('create_at', '发布时间')->datetime();
            });


        });

    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Admin::form(Community::class, function (Form $form) {

            $form->display('id', 'ID');

        });
    }

    public function detail($id)
    {

        $data = Community::where('community_id', $id)
            ->with('user')
            ->with('gifts')
            ->first();

        if ($data) {
            $data = $data->toArray();
        } else {
            abort(404);
        }


        if ($data['gifts']) {

            $user_ids = array_unique(array_column($data['gifts'], 'user_id'));
            $gift_ids = array_unique(array_column($data['gifts'], 'gift_id'));
            $tag_ids = array_unique(array_column($data['gifts'], 'tag'));

            $user_list = User::whereIn('id', $user_ids)->select(['id', 'username', 'avatar'])->get();
            $user_data = [];
            if ($user_list) {
                $user_list = $user_list->toArray();
                foreach ($user_list as $key => $val) {
                    $user_data[$val['id']] = $val;
                }
            }

            $gift_list = Gift::whereIn('gift_id', $gift_ids)->select(['gift_id', 'name', 'icon'])->get();
            $gift_data = [];
            if ($gift_list) {
                $gift_list = $gift_list->toArray();
                foreach ($gift_list as $key => $val) {
                    $gift_data[$val['gift_id']] = $val;
                }
            }

            $tag_list = Tag::whereIn('atag_id', $tag_ids)->select(['atag_id', 'name'])->get();
            $tag_data = [];
            if ($tag_list) {
                $tag_list = $tag_list->toArray();
                foreach ($tag_list as $key => $val) {
                    $tag_data[$val['atag_id']] = $val;
                }
            }

            foreach ($data['gifts'] as $key => $val) {
                if (isset($user_data[$val['user_id']])) {
                    $data['gifts'][$key]['username'] = $user_data[$val['user_id']]['username'];
                    $data['gifts'][$key]['avatar'] = $user_data[$val['user_id']]['avatar'];
                }
                if (isset($gift_data[$val['gift_id']])) {
                    $data['gifts'][$key]['gift_name'] = $gift_data[$val['gift_id']]['name'];
                    $data['gifts'][$key]['gift_icon'] = $gift_data[$val['gift_id']]['icon'];
                }
                if (isset($tag_data[$val['tag']])) {
                    $data['gifts'][$key]['tag_name'] = $tag_data[$val['tag']]['name'];
                }
            }
        }

        $page = 1;
        //设置每页显示条数
        $limit = 10;

        $count = Community\Comment::where('parent_id', $id)->count();
        $sums = ceil($count / $limit);

        //设置上一页、下一页
        $prev = ($page - 1) > 0 ? $page - 1 : 1;
        $next = ($page + 1) < $sums ? $page + 1 : $sums;

        //求偏移量
        $offset = ($page - 1) * $limit;

        //sql查询数据库
        $comments = Community\Comment::where('parent_id', $id)
            ->orderBy('com_id', 'desc')
            ->offset($offset)
            ->limit($limit)
            ->get();

        //数字分页(可有可无)
        $pp = array();
        for ($i = 1; $i <= $sums; $i++) {
            $pp[$i] = $i;
        }

        $data['comments'] = ['data' => $comments, 'prev' => $prev, 'next' => $next, 'sums' => $sums, 'pp' => $pp, 'page' => $page];

        return view('admin.statistics.nearby-detail', compact('data'));
    }

    public function addComment(Request $request)
    {
        /*$this->validate($request, [
            'code' => [function ($attribute, $value, $fail) {
                if ($value <= 10) {
                    $fail(':attribute needs more cowbell!');
                }
            },'required']
        ]);*/
        $name = $request->post('name', Admin::user()->username);
        $community_id = $request->post('community_id');
        $telephone = $request->post('telephone');
        $content = $request->post('content');

        $flag = true;
        $message = '';

        if (!$content) {
            $flag = false;
            $message = '回复内容不能为空';
        }

        if (!$name) {
            $flag = false;
            $message = '用户名不能为空';
        }

        if (!$community_id) {
            $flag = false;
            $message = '参数错误';
        } else {
            $community = Community::find($community_id);
            if (!$community) {
                $flag = false;
                $message = '班务不存在或已被删除';
            }
        }

        if ($flag) {
            $comment = new Community\Comment();
            $comment->parent_id = $community_id;
            $comment->type = 1;
            $comment->content = $content;
            $comment->user_id = Admin::user()->id;
            $comment->user_name = $name;
            $comment->user_icon = Admin::user()->avatar;
            $flag = $comment->save();
            if ($flag) {
                return response()->json([
                    'status' => true,
                    'message' => '提交成功'
                ]);
            } else {
                return response()->json([
                    'status' => false,
                    'message' => '提交失败'
                ]);
            }

        } else {
            return response()->json([
                'status' => false,
                'message' => $message
            ]);
        }
    }

    public function getComment(Request $request)
    {
        $id = $request->get('id');
        $page = $request->get('page', 1);
        //设置每页显示条数
        $limit = $request->get('count', 10);

        $count = Community\Comment::where('parent_id', $id)->count();
        $sums = ceil($count / $limit);

        //设置上一页、下一页
        $prev = ($page - 1) > 0 ? $page - 1 : 1;
        $next = ($page + 1) < $sums ? $page + 1 : $sums;

        //求偏移量
        $offset = ($page - 1) * $limit;

        //sql查询数据库
        $data = Community\Comment::where('parent_id', $id)
            ->orderBy('com_id', 'desc')
            ->offset($offset)
            ->limit($limit)
            ->get();

        //数字分页(可有可无)
        $pp = array();
        for ($i = 1; $i <= $sums; $i++) {
            $pp[$i] = $i;
        }

        $data = ['data' => $data, 'prev' => $prev, 'next' => $next, 'sums' => $sums, 'pp' => $pp, 'page' => $page];
    }
}